#!/usr/bin/env python
# -*- coding: utf-8 -*-
###################################################################
# Author: wang donghao
# Date  : 2020.12
# Email : dd.parkhere@gmail.com
###################################################################

import os
import pprint

from dayu_widgets.qt import *
from dayu_widgets.combo_box import MComboBox
from dayu_widgets.tool_button import MToolButton
from dayu_widgets.label import MLabel
from dayu_widgets.line_edit import MLineEdit
from dayu_widgets.menu import MMenu
from dayu_widgets.push_button import MPushButton
from dayu_widgets.theme import MTheme
from widgets import utils
from dayu_widgets.progress_bar import MProgressBar
from widgets import page
from operator import methodcaller


class FetchDataThread(QThread):
    result_sig = Signal(list)

    def __init__(self, mode='', data=[]):
        super(FetchDataThread, self).__init__()
        self.mode = mode
        self.data = data

    def run(self, *args, **kwargs):
        sg = utils.get_sg_instance()
        result = methodcaller(self.mode, *self.data)(sg)
        self.result_sig.emit(result)


class DownloadThread(QThread):
    progress = Signal(list)

    def __init__(self, uploaded_movies=[], dst_path=''):
        super(DownloadThread, self).__init__()
        self.uploaded_movies = uploaded_movies
        self.dst_path = dst_path

    def run(self, *args, **kwargs):
        sg = utils.get_sg_instance()
        i = 0.0
        for m in self.uploaded_movies:
            r = sg.download_attachment(m, file_path=self.dst_path+'/'+m.get('name'))
            i += 1.0
            self.progress.emit([r, i*100.0/len(self.uploaded_movies)])


class SGDownloadManagerWin(QDialog):
    def __init__(self, parent=None):
        super(SGDownloadManagerWin, self).__init__(parent)

        self._init_ui()

    def _init_ui(self):
        self.setMinimumSize(1500, 900)
        self.setWindowTitle(u'SG下载器')
        self.setWindowIcon(QIcon(os.environ['WOKWOK_ROOT'] + '/resources/icons/main.png'))
        main_layout = QVBoxLayout()
        top_lay = QHBoxLayout()
        main_layout.addLayout(top_lay)

        self.proj_lb = MLabel(u'选择项目：')
        top_lay.addWidget(self.proj_lb)
        self.proj_cb = MComboBox()
        top_lay.addWidget(self.proj_cb)
        self.proj_cb.setMaximumWidth(100)
        self.proj_menu = MMenu()
        self.proj_cb.set_menu(self.proj_menu)



        self.sheet = page.SheetContent()
        self.sheet.table.set_no_data_image('')
        self.sheet.table.set_no_data_text(u'请先选择项目')
        self.sheet.fetch_data_thread = FetchDataThread()
        self.sheet.fetch_data_thread.result_sig.connect(self.sheet.get_fetch_result)
        self.sheet.show_msg = True
        self.sheet.setMinimumWidth(1300)
        self.sheet.table.selection_changed.connect(self.change_current_item)

        search_lay = QFormLayout()
        self.search_le = MLineEdit()
        self.search_le.setMaximumWidth(100)
        self.search_le.sig_delay_text_changed.connect(self.sheet.model_sort.set_search_pattern)
        search_lay.addRow(u'输入关键字搜索', self.search_le)

        top_lay.addLayout(search_lay)

        top_lay.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Minimum))

        # self.refresh_tb = MToolButton()
        # self.refresh_tb.set_dayu_svg(os.environ['WOKWOK_ROOT'] + '/resources/icons/refresh.png')
        # self.refresh_tb.clicked.connect(self.sheet.parse_config)
        # top_lay.addWidget(self.refresh_tb)

        middle_lay = QHBoxLayout()
        # middle_lay.addLayout(search_lay)
        middle_lay.addWidget(self.sheet)

        main_layout.addLayout(middle_lay)

        path_lay = QHBoxLayout()
        path_lb = MLabel(u'选择路径')
        path_lay.addWidget(path_lb)
        self.path_le = MLineEdit().folder()
        path_lay.addWidget(self.path_le)

        main_layout.addLayout(path_lay)

        self.progress_bar = MProgressBar()
        main_layout.addWidget(self.progress_bar)

        down_lay = QHBoxLayout()
        down_lay.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Minimum))
        self.ok_pb = MPushButton(u'下载')
        down_lay.addWidget(self.ok_pb)
        down_lay.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Minimum))

        main_layout.addLayout(down_lay)

        self.setLayout(main_layout)
        MTheme('light').apply(self)

        self.page_data = {"page_actions": [],
                      "page_fields": [],
                      "page_filters": [],
                      "page_type": 'Version',
                 }

        self.proj_cb.sig_value_changed.connect(self.change_proj)
        self.ok_pb.clicked.connect(self.start_download)

        self.project_dict = {}

        self.find_proj_thread = utils.MFetchDataThread('find', ['Project', [['sg_status', 'is', 'Active']], ['name']])
        self.find_proj_thread.result_sig.connect(self.set_proj)
        self.find_proj_thread.start()

        self.download_thread = DownloadThread()
        self.download_thread.progress.connect(self.get_download_progress)

    def set_proj(self, result):
        self.proj_menu.set_data([p.get('name') for p in result])
        for r in result:
            self.project_dict[r.get('name')] = r

    def change_proj(self, proj):
        self.page_data['page_fields'] = [{'searchable': True, 'key': 'code', 'label': u'版本名'},
                                                  {'searchable': True, 'key': 'entity', 'label': u'链接'},
                                                  {'searchable': True, 'key': 'sg_uploaded_movie', 'label': u'已上传文件'},
                                                  {'searchable': True, 'key': 'description', 'label': u'说明'},
                                                  {'searchable': True, 'key': 'sg_status_list', 'label': u'状态'},
                                                  {'searchable': True, 'key': 'sg_qt_status', 'label': u'qt状态'},
                                                  {'searchable': True, 'key': 'sg_mhy_status', 'label': u'mhy状态'},
                                                  {'searchable': True, 'key': 'created_at', 'label': u'创建日期'},
                                                  {'searchable': True, 'key': 'updated_at', 'label': u'更新日期'},
                                                  ]
        self.page_data['page_filters'] = [['project', 'name_is', proj], ['sg_status_list', 'is', 'kcheck'], ['entity', 'type_is', 'Asset']]
        self.sheet.set_config(self.page_data)
        self.sheet.parse_config()
        pass

    def start_download(self):
        selected = self.sheet.get_selected_content()
        if not selected:
            return
        dst_path = self.path_le.text().replace('\\', '/')
        if not dst_path:
            return
        if not os.path.isdir(dst_path):
            os.makedirs(dst_path)
        movies = [e.get('sg_data').get('sg_uploaded_movie') for e in selected]
        self.download_thread.uploaded_movies = movies
        self.download_thread.dst_path = dst_path
        self.download_thread.start()
        self.ok_pb.setText(u'正在下载')
        self.ok_pb.setEnabled(False)
        print u'正在下载'

    def change_current_item(self):
        self.sheet.table.setEnabled(False)
        self.sheet.table.setEnabled(True)

    def get_download_progress(self, progress):
        self.progress_bar.setValue(progress[1])
        if progress[1] == 100:
            self.progress_bar.set_dayu_status(MProgressBar.SuccessStatus)
            self.ok_pb.setText(u'下载成功！')


if __name__ == '__main__':
    import sys
    from dayu_widgets.qt import QApplication

    app = QApplication(sys.argv)
    test = SGDownloadManagerWin()
    from dayu_widgets.theme import MTheme
    light = MTheme('light')
    light.apply(test)
    test.show()
    sys.exit(app.exec_())






